namespace Microsoft.ServiceModel.Samples.Discovery
{
    using System;
    using System.Xml;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Description;

    [AttributeUsage(AttributeTargets.Class)]
    public sealed class DiscoverableAttribute : Attribute, IServiceBehavior
    {
        #region IServiceBehavior Members

        void IServiceBehavior.AddBindingParameters(
            ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, 
            Collection<ServiceEndpoint> endpoints, 
            BindingParameterCollection bindingParameters)
        {
     
        }

        void IServiceBehavior.ApplyDispatchBehavior(
            ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            if (serviceHostBase == null)
                throw new ArgumentNullException("serviceHostBase");

            if (serviceHostBase.Extensions.Find<DiscoveryServiceExtension>() 
                    == null)
            {
                List<ServiceProperties> serviceProperties = 
                    new List<ServiceProperties>();
                

                foreach (ServiceEndpoint endpoint in serviceDescription.Endpoints)
                {
                    ServiceProperties props = 
                        new ServiceProperties(endpoint.Address);

                    props.Types = new ContactTypeCollection();
                    props.Types.Add(new XmlQualifiedName(endpoint.Contract.Name,
                        endpoint.Contract.Namespace));
                    serviceProperties.Add(props);
                }

                DiscoveryServiceExtension extension = 
                    new DiscoveryServiceExtension(serviceProperties);

                serviceHostBase.Extensions.Add(extension);
            }
        }

        void IServiceBehavior.Validate(ServiceDescription serviceDescription, 
            ServiceHostBase serviceHostBase)
        {
     
        }

        #endregion
    }
}
